package config

import (
	"gopkg.in/yaml.v3"
	"os"
)

var (
	SysConfig *Config
)

type Config struct {
	Server ServerConfig      `yaml:"server"`
	DB     DBConfig          `yaml:"db"`
	Logger MysqlLoggerConfig `yaml:"sqlLogger"`
	AIModel AIModelConfig     `yaml:"AIModel"`
}

type ServerConfig struct {
	Env     string `yaml:"env"`
	Address string `yaml:"address"`
	Port    int    `yaml:"port"`
}

type DBConfig struct {
	Host     string `yaml:"host"`
	Port     int    `yaml:"port"`
	Name     string `yaml:"name"`
	User     string `yaml:"user"`
	Password string `yaml:"password"`
	Migrate  bool   `yaml:"migrate"`
}

type MysqlLoggerConfig struct {
	SlowThreshold          int    `yaml:"slow_threshold"`            // 慢SQL阈值
	LogLevel               string `yaml:"log_level"`                 // 日志级别
	IgnoreNotFoundError    bool   `yaml:"ignore_record_not_found"`   // 忽略未找到记录错误
	UseParametrizedQueries bool   `yaml:"use_parameterized_queries"` // 使用参数化查询
	Colorful               bool   `yaml:"colorful"`                  // 是否启用彩色输出，默认关闭
}

type AIModelConfig struct {
	URL           string `yaml:"url"`
	VersionModel  string `yaml:"version_model"`
	ThinkingModel string `yaml:"thinking_model"`
}

func init() {
	appConfig := "config/app.yaml"
	cfg, err := ConfigParse(&appConfig)
	if err != nil {
		panic("初始化配置失败 : " + err.Error())
	}
	SysConfig = cfg
}

func ConfigParse(appConfig *string) (*Config, error) {
	config := &Config{}

	file, err := os.Open(*appConfig)
	if err != nil {
		return nil, err
	}
	defer func(file *os.File) {
		err := file.Close()
		if err != nil {
			panic("文件异常关闭")
		}
	}(file)

	if err := yaml.NewDecoder(file).Decode(&config); err != nil {
		return nil, err
	}

	return config, nil
}
